import { defineStore } from "pinia";
import { ref } from "vue";
import http from "@/utils/http.js";
import router from "@/router";


export const userStore = defineStore("userStore",() => {
      //定义仓库：状态
      const userInfo = ref({});

//使用async和await
    //验证用户
    const getUserInfo = async ({userName,userPassword}) => {
        const res = await http.post('/users/login', {userName,userPassword})
        if(res.code == 666){
            userInfo.value = res
            console.log(userInfo.value)
        } else {
            userInfo.value={}
            await router.replace({path: '/login'})
        }
    }
    const clearUserInfo = () => {
        userInfo.value = {}
    }

    const updateUserInfo = async (userId) => {
        const res = await http.get('/users/' + userId)
        if (res.code === 666) {
            userInfo.value = res
        }
    }

    return {    //返回数据
        userInfo,
        getUserInfo,
        clearUserInfo,
        updateUserInfo
    }
}, {
    persist: true       //持久化存储
})